package com.faiz.picturebed.service.impl;

import com.faiz.picturebed.exception.FileTypeNotSupportException;
import com.faiz.picturebed.service.ParseMDService;
import com.faiz.picturebed.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Service
public class ParseMDServiceImpl implements ParseMDService {

    private final PictureService pictureService;


    @Autowired
    public ParseMDServiceImpl(PictureService pictureService) {
        this.pictureService = pictureService;
    }

    @Override
    public void parseMD(MultipartFile file, HttpServletResponse response) throws FileTypeNotSupportException, IOException {
        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;
        String fileSuffix = Objects.requireNonNull(file.getOriginalFilename()).substring(originalFileName.lastIndexOf("."));
        String picturePath = "";
        if (fileSuffix.equals(".md")) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = "";
            StringBuilder out = new StringBuilder();
            while (true) {
                try {
                    if ((line = bufferedReader.readLine()) == null) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 这一行是图片
                if (line.contains("![")) {
                    // 将本地的图片转换为为远程的图片
                    picturePath = line.substring(line.lastIndexOf("(") + 1, line.lastIndexOf(")"));
                    String pictureName = picturePath.substring(picturePath.lastIndexOf("\\") + 1);
                    File picture = new File(picturePath);
                    MultipartFile pictureFile = new MultipartFile() {
                        @Override
                        public String getName() {
                            return null;
                        }

                        @Override
                        public String getOriginalFilename() {
                            return pictureName;
                        }

                        @Override
                        public String getContentType() {
                            return null;
                        }

                        @Override
                        public boolean isEmpty() {
                            return false;
                        }

                        @Override
                        public long getSize() {
                            return 0;
                        }

                        @Override
                        public byte[] getBytes() throws IOException {
                            return new byte[0];
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return new FileInputStream(picture);
                        }

                        @Override
                        public void transferTo(File file) throws IOException, IllegalStateException {

                        }
                    };
                    String url = pictureService.uploadPicture(pictureFile);
                    line = line.replace(picturePath, url);

                }
                out.append(line);
                out.append("\n");
            }
            bufferedReader.close();

            String PATH = "./remote-md/";
            File folder = new File(PATH);

            if (!folder.exists() && !folder.mkdir()) System.out.println("文件夹创建失败！！！");

            File remoteMDFile = new File(PATH + "/" +originalFileName.replace(".md", "") + "-remote.md");


            FileOutputStream writer = new FileOutputStream(remoteMDFile);
            writer.write(out.toString().getBytes(StandardCharsets.UTF_8));
            writer.close();


            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + remoteMDFile.getName());// 设置文件名
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            byte[] buffer = new byte[1024];
            try {
                fis = new FileInputStream(remoteMDFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                assert fis != null;
                fis.close();
                assert bis != null;
                bis.close();
            }


//            System.out.println(out);

        } else {
            throw new FileTypeNotSupportException(50000, "不支持除.md文件类型外的其他文件");
        }
    }
}
